package com.stn.zjx.givingtreasure.activity.userbankcard;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.web.GenericWebActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.bean.BankCard;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.BankCardEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.UserBankCardApi;
import com.stn.zjx.givingtreasure.net.impl.UserBankCardNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxRegTool;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ModifyUserBankCardActivity extends BaseActivity {


    //正在发送中
    boolean isSendLoading = false;
    int seconds = 60;
    Disposable sendvalidate__disposable = null;
    @BindView(R.id.validate_bt)
    TextView validateBt;
    @BindView(R.id.validate_edit)
    EditText validateEdit;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.skip_bt)
    TextView skipBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.scan_bt)
    RelativeLayout scanBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.search_iv)
    ImageView searchIv;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.search_bg)
    RelativeLayout searchBg;
    @BindView(R.id.save_bt)
    TextView saveBt;
    @BindView(R.id.bank_card_tv)
    TextView bankCardTv;
    @BindView(R.id.real_name_edit)
    EditText realNameEdit;
    @BindView(R.id.id_card_edit)
    EditText idCardEdit;
    @BindView(R.id.phone_edit)
    EditText phoneEdit;
    @BindView(R.id.go_bind_bt)
    Button goBindBt;
    private EventHandler eh;

   private Integer userBankCardId=0;
    private String userBankCardNo="";
    private String userBankCardName="";
    private String userIdCard="";
    private String userRealName="";

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initComponent() {
        userBankCardId= getIntent().getIntExtra("userBankCardId",0);
        userRealName=getIntent().getStringExtra("userRealName");
        userIdCard=getIntent().getStringExtra("userIdCard");
        userBankCardName=getIntent().getStringExtra("userBankCardName");
        userBankCardNo=getIntent().getStringExtra("userBankCardNo");
        actionTitle.setText(getString(R.string.modify_bank_card_phone));
         bankCardTv.setText(""+userBankCardName+"("+getString(R.string.dialog_bank_card_modfiy_c2)
                 +
                 userBankCardNo.substring(userBankCardNo.length()-4,
                         userBankCardNo.length())
                 +")");
         idCardEdit.setText(userIdCard);
         idCardEdit.setSelection(idCardEdit.getText().length());
         realNameEdit.setText(userRealName);
         realNameEdit.setSelection(realNameEdit.getText().length());

        //发送验证码
        validateBt.setOnClickListener(v -> {
            if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {
                showToast(getString(R.string.please_input_bank_card_phone));
                return;
            }
            if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {
                showToast(getString(R.string.please_input_trust_phone));
                return;
            }
            sendValidate();
            SMSSDK.getVerificationCode("86", String.valueOf(phoneEdit.getText().toString().trim()));
        });
        //监听注册
        eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                //回调完成
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //提交验证码成功
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                User onlineUser = UserService.getInstance(ModifyUserBankCardActivity.this)
                                        .getOnlineLoginUser();
                                if (onlineUser == null) {
                                    return;
                                }
                                modify_bank_card(onlineUser.getToken(),
                                        realNameEdit.getText().toString().trim(),
                                        idCardEdit.getText().toString().trim(),
                                        phoneEdit.getText().toString().trim()
                                );
                            }
                        });


                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        runOnUiThread(() -> {

                            showToast(getString(R.string.sms_send_wait));
                        });

                    }
                } else {
                    runOnUiThread(() -> {
                        String str = ((Throwable) data).getMessage();
                        try {
                            JSONObject jb = new JSONObject(str);
                            showToast(jb.getString("detail"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    });
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调


        goBindBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(realNameEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_input_bank_card_real_name));
                    return;
                }
                if (TextUtils.isEmpty(idCardEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_input_id_card));
                    return;
                }
                if (!RxRegTool.isIDCard18(idCardEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_check_is_id_card_18));
                    return;
                }

                if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_input_bank_card_phone));
                    return;
                }
                if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_input_trust_phone));
                    return;
                }
                if (TextUtils.isEmpty(validateEdit.getText().toString().trim())) {
                    showToast(getString(R.string.sms_isnotempty));
                    return;
                }
                SMSSDK.submitVerificationCode("86", phoneEdit.getText().toString().trim(),
                        validateEdit.getText().toString().trim());
            }
        });


    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_edit_bank_card);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
        }
    }


    //重置发送短信按钮
    public void reset_sendValidate() {
        isSendLoading = false;
        validateBt.setText(getString(R.string.get_validate));
        validateBt.setBackgroundResource(R.drawable.round_default_theme_bg);
        seconds = 60;
        validateBt.setClickable(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (eh != null) {
            SMSSDK.unregisterEventHandler(eh);
        }
        if (sendvalidate__disposable != null) {
            sendvalidate__disposable.dispose();
            reset_sendValidate();
        }
    }

    //发送短信验证
    @SuppressLint("SetTextI18n")
    public void sendValidate() {
        sendvalidate__disposable = Observable.create((ObservableOnSubscribe<Integer>) observableEmitter -> {
            while (isSendLoading && seconds > 0) {
                seconds--;
                observableEmitter.onNext(seconds);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    sendvalidate__disposable.dispose();
                    e.printStackTrace();
                }
            }
            observableEmitter.onComplete();
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    isSendLoading = true;
                    validateBt.setBackgroundResource(R.drawable.round_darkgray_bg);
                    validateBt.setClickable(false);

                })
                .subscribe(seconds -> {
                    isSendLoading = true;
                    validateBt.setText(getString(R.string.surplus)
                            + "" + seconds + getString(R.string.seconds)
                            + getString(R.string.resend));
                }, throwable -> {
                    sendvalidate__disposable.dispose();
                    reset_sendValidate();
                }, this::reset_sendValidate);


    }


    public void modify_bank_card(String token, String userRealName, String userIdCard, String userPhone) {
        UserBankCardNetImpl
                .modify_bank_card(token,userBankCardId, userIdCard, userRealName, userPhone, token + "_modify_bank_card"
                        , new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                switch (domain.getStatus()) {
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                        BankCardEvent event = new BankCardEvent();
                                        EventBus.getDefault().post(event);
                                        finish();
                                        break;
                                    default:
                                        showToast(domain.getMessage());
                                        break;
                                }
                            }
                        });
    }
}
